package com.lst.api.controller;

import com.lst.api.exception.RequestParamErrorException;
import com.lst.api.service.IFileUploadService;
import com.lst.tools.custom.annotation.TokenPermission;
import com.lst.tools.custom.context.BaseContextHandler;
import com.lst.tools.custom.vo.JsonResponse;
import com.lst.tools.web.annotation.WebLog;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 文件上传记录表控制层
 *
 * @author Frank
 * @date 2019-12-30 10:31:37
 * @version: V1.0
 */
@Api(tags = "文件上传记录表控制层")
@RestController
@RequestMapping(value = "/fileUpload")
public class FileUploadController {

    @Autowired
    private IFileUploadService fileUploadService;

    @ApiOperation(value = "文件上传")
    @PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "access-token", value = "登录token", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "bizeType", value = "业务类型，例如上传头像时传'avatar', 相册时传'album',跟接口提供者定义", required = true, dataType = "String")
    })
    @TokenPermission
    @WebLog
    public JsonResponse<String> fileUpload(@RequestParam(value = "bizeType") String bizeType,
                                           @ApiParam(value = "文件对象数组", required = true) MultipartFile file) throws Exception {
        if (StringUtils.isBlank(bizeType)) {
            throw new RequestParamErrorException("bizeType不能为空！");
        }
        long userId = BaseContextHandler.getUserId();
        String originalFilename = file.getOriginalFilename();
        String format = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String fileUrl = fileUploadService.fileUpload(userId, bizeType, originalFilename, format, file.getInputStream());
        return JsonResponse.success(fileUrl);
    }
    
}